package com.thermal.thermal_inspection.controller;

import com.thermal.thermal_inspection.vo.IceCandidateMessage;
import com.thermal.thermal_inspection.vo.OfferAnswerMessage;
import com.thermal.thermal_inspection.vo.RegisterMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
@Slf4j
public class SignalingController {

    private final SimpMessagingTemplate messagingTemplate;

    public SignalingController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/register")
    public void handleRegister(SimpMessageHeaderAccessor headerAccessor) {
        String sessionId = getSessionId(headerAccessor);
        log.info("Registering client: {}", sessionId);

        messagingTemplate.convertAndSendToUser(
                sessionId,
                "/queue/id",
                new RegisterMessage(sessionId, sessionId)
        );
    }

    @MessageMapping("/offer")
    public void handleOffer(OfferAnswerMessage message, SimpMessageHeaderAccessor headerAccessor) {
        String from = getSessionId(headerAccessor);
        log.info("Forwarding offer from {} to {}", from, message.getTo());

        messagingTemplate.convertAndSendToUser(
                message.getTo(),
                "/queue/offer",
                new OfferAnswerMessage(from, message.getTo(), message.getOffer(), null)
        );
    }

    @MessageMapping("/answer")
    public void handleAnswer(OfferAnswerMessage message, SimpMessageHeaderAccessor headerAccessor) {
        String from = getSessionId(headerAccessor);
        log.info("Forwarding answer from {} to {}", from, message.getTo());

        messagingTemplate.convertAndSendToUser(
                message.getTo(),
                "/queue/answer",
                new OfferAnswerMessage(from, message.getTo(), null, message.getAnswer())
        );
    }

    @MessageMapping("/ice-candidate")
    public void handleIceCandidate(IceCandidateMessage message, SimpMessageHeaderAccessor headerAccessor) {
        String from = getSessionId(headerAccessor);
        log.info("Forwarding ICE candidate from {} to {}", from, message.getTo());

        messagingTemplate.convertAndSendToUser(
                message.getTo(),
                "/queue/ice-candidate",
                new IceCandidateMessage(from, message.getTo(), message.getCandidate())
        );
    }

    private String getSessionId(SimpMessageHeaderAccessor headerAccessor) {
        return headerAccessor.getUser().getName();
    }
}